<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8"/>
	<title>图片合成</title>
</head>
<body>
	<div>
		<div>记大仇：<textarea id="text" style="height: 100px;width:400px">假如生活欺骗了你，请不要悲伤！thank you!</textarea></div>
		<div><button onclick="build()">生成</button></div>
	</div>
	<div>
		<canvas id="canvas" height="800" width="800"></canvas>
	</div>
	<script type="text/javascript">
		var fileupload = document.getElementById('fileupload')
		var canvas = document.getElementById('canvas')
		var amount = document.getElementById('amount')
		var text = document.getElementById('text')

		var bqb = ''

		var context = canvas.getContext('2d')
		build()
		function build(){
			var img = new Image()
		   	img.onload = function(){
			    var canvasWidth = canvas.width;//计算canvas的宽度
			    var padding = 60
			    var lineWidth = 0
			    var lastSubStrIndex = 0
				canvas.width = img.width
		   		context.fillStyle="#000000";
				context.lineWidth=1; 
	    		context.font = "30px Microsoft YaHei"
				var initHeight=img.height + 50;//绘制字体距离canvas顶部初始的高度
	    		var str = text.value
				for(let i=0;i<str.length;i++){ 
				    lineWidth+=context.measureText(str[i]).width; 
				    if(lineWidth>canvasWidth - padding * 2){  
				        initHeight+=40;//20为字体的高度
				    } 
				    if(i==str.length-1){//绘制剩余部分
				        initHeight+=60;//20为字体的高度
				    }
				}
				console.log(initHeight)
				canvas.height = initHeight
			    context.fillStyle = "#fff";
				context.fillRect(0, 0, canvas.width, canvas.height);
		   		context.drawImage(img, 0, 0)
	    		context.fillStyle="#000000";
				context.lineWidth=1; 
	    		context.font = "30px Microsoft YaHei"
				lineWidth = 0;
				initHeight=img.height + 50;//绘制字体距离canvas顶部初始的高度
				lastSubStrIndex = 0; //每次开始截取的字符串的索引
				var strList = []
				canvasWidth = canvas.width;//
				for(let i=0;i<str.length;i++){ 
				    lineWidth+=context.measureText(str[i]).width; 
				    if(lineWidth>canvasWidth - padding * 2){  
				    	console.log(i)
				        context.fillText(str.substring(lastSubStrIndex,i),padding,initHeight);//绘制截取部分
				        initHeight+=40;//20为字体的高度
				        lineWidth=0;
				        lastSubStrIndex=i;
				    } 
				    if(i==str.length-1){//绘制剩余部分
				        context.fillText(str.substring(lastSubStrIndex,i+1),padding,initHeight);
				    }
				}
			}
			img.src = bqb;
		}
	</script>
</body>
</html>